import { asyncRoutes, constantRoutes } from '@/router'
import { getRouter } from '@/api/user'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const newRoute = []
function showRoute(data) {
  const routeArr = []
  for (let index = 0; index < data.length; index++) {
    if (data[index].status == 2) {
      continue
    }
    const route = {
      path: data[index]['path'],
      component: '',
      name: data[index]['name'],
      meta: { title: data[index]['name'], icon: data[index]['icon'] },
      children: [],
      hidden: false
    }
    if (!data[index]['component']) {
      route['component'] = Layout
    } else {
      route['component'] = resolve => require([`@/views${data[index]['component']}`], resolve)
    }
    if (data[index].child && data[index].child.length > 0) {
      route['children'] = showRoute(data[index].child)
    }
    if (data[index].pid == 0) {
      newRoute.push(route)
    } else {
      routeArr.push(route)
    }
  }
  return routeArr
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      getRouter().then(response => {
        const { data } = response
        showRoute(data)
        let accessedRoutes
        accessedRoutes = newRoute || []
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
